package com.draven.common;

import com.draven.utils.JsonDateValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * Created by Draven on 2017/4/11.
 * E-mail:draven1122@163.com s
 */
public class BaseController {

    public ModelAndView ajax(Integer statusCode, String message) {
        ModelAndView modelAndView = new ModelAndView("/jsonData");
        modelAndView.addObject("statusCode", statusCode);
        modelAndView.addObject("message", message);
        return modelAndView;
    }

    public ModelAndView ajaxDoneSuccess(String message){
        return ajax(200,message);
    }

    public  ModelAndView ajaxDoneError(String message){
        return ajax(300,message);
    }

    public  ModelAndView ajaxJson(String jsonData){
        ModelAndView modelAndView = new ModelAndView("/json");
        modelAndView.addObject("jsonData", jsonData);
        return modelAndView;
    }

    public boolean isNullOrBlank(String str){
        return str==null||"".endsWith(str);
    }

    public String listToJsonArrayStr(List data){
        String jsonStr = "";
        if ( data != null && data.size()!=0){
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss"));
            JSONArray jsonArray = JSONArray.fromObject(data,jsonConfig);
            jsonStr = jsonArray.toString();
        }else{
            jsonStr = "[]";
        }
        return jsonStr;
    }
    public String listToJsonStrWithTotalCount(List data){
        String jsonStr = "";
        String jsonString="";
        if ( data != null && data.size()!=0){
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss"));
            JSONArray jsonArray = JSONArray.fromObject(data,jsonConfig);
            jsonStr = jsonArray.toString();
            jsonString = "{\"totalCount\":"+data.size()+",\"rows\":"+jsonStr+"}";
        }else{
            jsonString = "{\"totalCount\":0,\"rows\":[]}";
        }
        return jsonString;
    }
    public <T> T getSessionValue(HttpServletRequest request,String key){
        return (T)request.getSession().getAttribute(key);
    }
}

